package cn.melonlib.cores.commons.comp.utils;

import cn.hutool.core.util.NumberUtil;
import org.apache.commons.lang3.StringUtils;
import org.intellij.lang.annotations.Language;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class DateTimeUtils {

    public static final Pattern expiresRegex=Pattern.compile("^(\\d+)(\\w)?$");
    public long expiresValue(String value){
        Matcher matcher=expiresRegex.matcher(value);
        if(matcher.matches()){
            int time= NumberUtil.parseInt(matcher.group(1));
            String flag= StringUtils.defaultIfBlank(matcher.group(2),"d").toLowerCase();
            if(time<0){
                return -1;
            }else if(time > 0){
                return switch (flag){
                    case "m"->{
                        Calendar now=Calendar.getInstance();
                        now.add(Calendar.MONTH,-time);
                        yield now.getTimeInMillis();
                    }
                    case "w"->{
                        Calendar now=Calendar.getInstance();
                        now.add(Calendar.WEEK_OF_YEAR,-time);
                        yield now.getTimeInMillis();
                    }
                    case "y"->{
                        Calendar now=Calendar.getInstance();
                        now.add(Calendar.YEAR,-time);
                        yield now.getTimeInMillis();
                    }
                    case "d" -> {
                        Calendar now=Calendar.getInstance();
                        now.add(Calendar.DAY_OF_YEAR,-time);
                        yield now.getTimeInMillis();
                    }
                    case "h"-> System.currentTimeMillis()-(time*3600000L);
                    case "i" -> System.currentTimeMillis()-(time*60000L);
                    case "s" -> System.currentTimeMillis()-(time*1000L);
                    default -> System.currentTimeMillis()-time;
                };
            }
            return 0;
        }else{
            return 0;
        }
    }
}
